<template>
  <div class="check-film-page">
    <modal-view
      title="影片库"
      v-model:visible="statusState.checkFilmVisible"
      size="small"
      okText="确定"
      cancelText="取消"
      :width="1006"
      :afterClose="afterCloseEdit"
      @confirm="filmConfirm"
      @cancel="filmCancel"
    >
      <div class="filter-box">
        <a-cascader
          :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          class="m-r-24"
          change-on-select
          :allowClear="false"
          :field-names="{ label: 'name', value: 'id', children: 'subcateg' }"
          :options="videoClassList"
          placeholder="全部分类"
          @change="handleSelectChange"
        >
          <template #suffixIcon>
            <a-tooltip placement="top" color="#fff">
              <template #title> 双击选中父级 </template>
              <div class="ellipsis-text"><question-circle-outlined /></div>
            </a-tooltip>
          </template>
        </a-cascader>
        <a-input
          :maxlength="19"
          :onkeyup="
            () => {
              if (filmListState.video_id) filmListState.video_id = filmListState.video_id.replace(/\D/g, '')
            }
          "
          :onafterpaste="
            () => {
              if (filmListState.video_id) filmListState.video_id = filmListState.video_id.replace(/\D/g, '')
            }
          "
          allowClear
          v-model:value="filmListState.video_id"
          class="width-196 m-l-24"
          placeholder="请输入影片ID"
        />
        <a-input
          allowClear
          v-model:value.trim="filmListState.video_keyword"
          class="width-196 m-l-24"
          placeholder="请输入影片名称关键词"
        />
      </div>
      <a-table
        id="classifyTable"
        :columns="filmColumn"
        :data-source="state.filmList"
        :loading="state.loading"
        :pagination="false"
        :scroll="{ x: 600 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'video_cover'">
            <div v-if="record.video_cover">
              <a-image
                width="37.6px"
                height="39.85px"
                class="w-[-webkit-fill-available] object-contain"
                :src="getIcon(record)"
                alt=""
              />
            </div>
            <span v-else>-</span>
          </template>
          <template v-else-if="column.key === 'video_popularity'">
            <span>
              {{ formatNumber(record.video_popularity) }}
            </span>
          </template>
          <template v-if="column.key === 'video_price_type'">
            {{ getPriceType(record) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <span>
              <a class="basicColor" @click="addItem(record)">添加 </a>
            </span>
          </template>
        </template>
      </a-table>
      <a-pagination
        @change="handlePaginationChange"
        show-size-changer
        :defaultPageSize="10"
        :pageSizeOptions="['10', '20', '50', '100']"
        :show-total="(total:number)=>`共${total}条`"
        class="flex justify-end mt-[8px]"
        :total="queryState.total"
      />
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import type { FilmListData } from '@/types/site/role'
import { formatNumber } from '@/utils/format'

import { computed, onMounted, reactive, ref, watch, inject } from 'vue'
import { filmColumn } from './dataSource'
import ModalView from '@/components/components/modal/ModalView.vue'
import { roleState, statusState } from '../../state'
import apis from '@/apis'
import { storage } from '@/utils/storage'
const {
  site: { classify_list, film_list }
} = apis
const emit = defineEmits(['getFilm'])
const props = withDefaults(defineProps<{ videoId?: any }>(), {
  videoId: undefined
})
const videoClassList = ref()
const baseUrl: any = inject('baseUrl')
const siteId = storage.get('siteId')
const queryState = reactive({
  offset: 0, // 默认当前页数
  limit: 10, // 默认当前页显示数据的大小
  total: 0 // 总数，必须先有
})
interface FilmListState {
  categ_id: string | undefined
  subcateg_id: string | undefined // 子分类
  video_id: string | undefined // 影片id
  video_keyword: string | undefined // 影片关键词
  site_id: string
  status: number
}
const filmListState = reactive<FilmListState>({
  categ_id: undefined,
  subcateg_id: undefined,
  video_id: undefined,
  video_keyword: undefined,
  site_id: siteId,
  status: 1
})
console.log('props.videoId: ', props.videoId)

const state = reactive({
  loading: false,
  filmList: [] as FilmListData[]
})

/**
 * 分页改变事件
 */
const handlePaginationChange = (size: number, limit: number) => {
  queryState.limit = limit
  queryState.offset = (size - 1) * limit
  getFilmList()
}
//获取分类接口
const getAtlasList = () => {
  classify_list({ site_id: siteId, categ_status: 1 }).then((res: any) => {
    if (res?.categ.length === 0) return []
    res?.categ.unshift({ id: undefined, name: '全部分类' })
    videoClassList.value = res?.categ.map((item: any) => {
      for (var key in item) {
        if (Array.isArray(item[key]) && item[key].length === 0) {
          delete item[key]
        }
      }
      return item
    })
  })
}
//影片分类change事件
const handleSelectChange = (value: any, selectedOptions: any) => {
  console.log('value[0]: ', value[0])
  console.log('value: ', value, selectedOptions)
  filmListState.categ_id = value.length > 0 && value[0] ? value[0] : undefined
  filmListState.subcateg_id = value.length > 0 && value[1] ? value[1] : undefined
  console.log(filmListState)
}
//查询影片
const getFilmList = () => {
  state.loading = true
  console.log('getActiveList')
  const params = { ...filmListState, ...queryState }
  if (!params.video_id) params.video_id = undefined
  film_list(params)
    .then((res: any) => {
      console.log('图集列表: ', res)
      state.filmList = res?.videos ?? []
      queryState.total = +res?.total ?? 0
      state.loading = false
      //处理下一页，第一条删除问题
      if (queryState.offset >= (res?.videos ?? 0) && queryState.total != 0) {
        queryState.offset -= queryState.limit
        getFilmList()
      }
    })
    .catch(() => {
      state.loading = false
    })
}
//防抖
const antiShake = (categ_id: any, id: any, keyword: any, time: number) => {
  return setTimeout(() => {
    console.log(`防抖：${categ_id}-${id}-${keyword}`)
    getFilmList()
  }, time)
}
let timer: any = null
watch([() => filmListState.categ_id, () => filmListState.video_id, () => filmListState.video_keyword], (value) => {
  if (value) {
    console.log('value: ', value)
    clearTimeout(timer)
    timer = antiShake(value[0], value[1], value[2], 500)
  }
})
//关闭弹窗重置
const afterCloseEdit = () => {
  filmListState.categ_id = undefined
  filmListState.subcateg_id = undefined
  filmListState.video_id = undefined
  filmListState.video_keyword = undefined
}
const filmConfirm = (value: any) => {
  console.log('value: ', value)
  statusState.checkFilmVisible = value
}
const filmCancel = () => {
  statusState.checkFilmVisible = false
}
const addItem = (item: any) => {
  emit('getFilm', item)
  statusState.checkFilmVisible = false
}
//根据类型获取图片
const getIcon = computed(() => (item: FilmListData) => {
  if (+item.video_cover_type == 1) return baseUrl + item.video_cover
  return item.video_cover
})
//获取收费状态
const getPriceType = computed(() => (item: any) => {
  if (item.video_price_type === 1) {
    return '免费'
  } else {
    return item.video_price + '金币'
  }
})
watch(
  () => props.videoId,
  (val: any) => {
    console.log('val: ', val)
    if (val) {
      filmListState.video_id = val
    }
  },
  { deep: true }
)
watch(
  () => statusState.checkFilmVisible,
  () => {
    getFilmList()
    getAtlasList()
  },
  { deep: true }
)
onMounted(() => {})
</script>

<style lang="less" scoped>
.filter-box {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 16px;

  .width-196 {
    width: 196px;
  }

  .m-l-24 {
    margin-left: 24px;
  }
}
</style>
